﻿using dbcTools.Tools;
using DBCTools.Tools;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;

namespace dbcTools
{
	/// <summary>
	/// MainWindow.xaml 的交互逻辑
	/// </summary>
	public partial class MainWindow : Window
	{
		public MainWindow()
		{
			InitializeComponent();
		}

		private loadConfig _config;



		private void DbcToCsv(string filePath)
		{
			dbcReader dbc = new dbcReader(filePath);

			string FileName = filePath.Substring(filePath.LastIndexOf("\\") + 1);

			string filestruct = _config.GetConf(FileName);

			if (filestruct == "")
				if (System.Windows.MessageBox.Show("[dbcTools.conf]中不存在文件[" + FileName + "]的结构配置,导出数据均为有符号整型(int).\n如果没问题的话按确认后继续!", "缺失配置数据", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
					return;

			if (filestruct != "" && filestruct.Length != dbc.ColumnCount)
			{
				System.Windows.MessageBox.Show("请在配置文件[dbcTools.conf]中正确填写dbc文件的结构");
				return;
			}

			StreamWriter sw = new StreamWriter("csv/" + FileName + ".csv");
			uint jdt = 0;
			if (filestruct != "")
			{
				foreach (var i in filestruct)
				{
					sw.Write(i.ToString() + ",");
				};
			}
			else
			{ 
				for (int i = 0; i < dbc.ColumnCount; i++)
				{ 
					sw.Write("i" + ",");
					filestruct += "i";
				}
			}

			sw.Write("\n");

			foreach (KeyValuePair<uint, byte[]> i in dbc.GetStore())
			{
				MemoryStream ms = new MemoryStream(i.Value);
				BinaryReader br = new BinaryReader(ms);

				for (uint ii = 0; ii < dbc.ColumnCount; ii++)
				{
						if (filestruct[(int)ii].ToString() == "u")
							sw.Write(br.ReadUInt32());
						else if (filestruct[(int)ii].ToString() == "i")
							sw.Write(br.ReadInt32());
						else if (filestruct[(int)ii].ToString() == "f")
							sw.Write(br.ReadSingle());
						else if (filestruct[(int)ii].ToString() == "b")
							sw.Write(br.ReadByte());
						else if (filestruct[(int)ii].ToString() == "s")
							sw.Write("\"" + dbc.GetText(br.ReadUInt32()) + "\"");
						else if (filestruct[(int)ii].ToString() == "x")
							sw.Write("0x" + Convert.ToString(br.ReadUInt32(), 16));
						else
							sw.Write(br.ReadInt32());
					
					if (ii+1 != dbc.ColumnCount)
						sw.Write(",");
				}
				sw.WriteLine();
				uint jdtval = (uint)(jdt++ * 100 / dbc.GetStore().Count + 1);

				SetProBar((jdtval));
				SetProBarMsg(FileName + " (" + jdtval + "%)");

			}
			sw.Close();
			SetProBar(0);
			SetProBarMsg("");
		}

		//dbc->csv
		private string _dbcfilePaths;
		private void button_Click(object sender, RoutedEventArgs e)
		{
			Thread dbctocsv = new Thread(dbcToCsv);
			_dbcfilePaths = dbcfilePaths.Text;
			dbctocsv.Start();
		}

		//csv->dbc
		private string _csvfilePaths;
		private void button3_Click(object sender, RoutedEventArgs e)
		{
			Thread csvtodbc = new Thread(csvToDbc);
			_csvfilePaths = csvfilePaths.Text;
			csvtodbc.Start();
		}

		private void csvToDbc()
		{
			StringReader sr = new StringReader(_csvfilePaths);

			string str = sr.ReadLine();

			while (str != null)
			{
				CsvToDbc(str);
				str = sr.ReadLine();
			}
		}

		private void CsvToDbc(string filePath)
		{
			csvReader csv = new csvReader(filePath,this);
			string FileName = filePath.Substring(filePath.LastIndexOf("\\") + 1);

		}

		private void dbcToCsv()
		{
			StringReader sr = new StringReader(_dbcfilePaths);

			string str = sr.ReadLine();

			while (str != null)
			{
				DbcToCsv(str);
				str = sr.ReadLine();
			}
		}


		//初始化载入配置
		private void MainWindows_Initialized(object sender, System.EventArgs e)
		{
			_config = new loadConfig();

			if (!Directory.Exists("CSV"))
				Directory.CreateDirectory("CSV");

			if (!Directory.Exists("DBC"))
				Directory.CreateDirectory("DBC");

			if (!Directory.Exists("SQL"))
				Directory.CreateDirectory("SQL");

			if (!Directory.Exists("outputDBC"))
				Directory.CreateDirectory("outputDBC");

		}

		public void SetProBar(uint val)
		{
			Dispatcher.Invoke(() =>{proBar.Value = val;});
		}

		public void SetProBarMsg(string Msg)
		{
			Dispatcher.Invoke(() =>{probarMsg.Content = Msg;});
		}

		private void button2_Click(object sender, RoutedEventArgs e)
		{
			OpenFileDialog dialog = new OpenFileDialog();
			dialog.InitialDirectory = Directory.GetCurrentDirectory() + "\\DBC";
			dialog.Filter = "DBC文件|*.DBC";
			dialog.AddExtension = true;
			dialog.Multiselect = true;

			if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
			{
				foreach (var i in dialog.FileNames)
				{
					dbcfilePaths.Text += i.ToString() + "\n";
				}
			}
		}

		private void button4_Click(object sender, RoutedEventArgs e)
		{
			OpenFileDialog dialog = new OpenFileDialog();
			dialog.InitialDirectory = Directory.GetCurrentDirectory() + "\\CSV";
			dialog.Filter = "CSV文件|*.CSV";
			dialog.AddExtension = true;
			dialog.Multiselect = true;

			if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
			{
				foreach (var i in dialog.FileNames)
				{
					csvfilePaths.Text += i.ToString() + "\n";
				}
			}
		}
	}
}
